<?php
namespace Core;
defined('ENV') || exit('illegal Access! @110');
/**
 * 视图类
 */
class View 
{
	public static $instance = false;
	public static $arrSysVar = array();
	public static $arrTplVar = array(); //存储模板变量

	public static $htmls = array();

	private function __construct()
	{}
	
	//备用初始化
	public static function init($arrSysVar)
	{
		self::$arrSysVar = $arrSysVar;
	}

	//获取模板文件的绝对路径
	public static function getRealPath($filename)
	{
		if (strpos($filename, '/')) {
			return VIEWPATH.$filename.TPL_FILE_EXTENSION;
		} else {
			return VIEWPATH.MODULE_NAME.'/'.$filename.TPL_FILE_EXTENSION;
		}
	}

    /**
     * 没有预渲染功能的显示函数
     * 用于显示登陆页或活动页等风格独特的页面
     */
	public static function display($filename='')
	{
		$filename = empty($filename) ? ACTION_NAME : $filename;
		$path = self::getRealPath($filename);
		$content = self::fetch($path);
		header("Content-type: text/html; charset=utf-8");
		exit($content);
	}
	
	//输出内容到变量
	public static function fetch($filepath)
	{
		//将变量置为本函数可访问(用于解析模版)
		extract(array_merge(self::$arrSysVar, self::$arrTplVar));

		ob_start();
		ob_implicit_flush(0);

		//渲染传入的模版
		include_once($filepath);

		$content = ob_get_contents(); //输出到变量, 并清除缓存
		ob_end_clean();
		return $content;
	}

	//记录要渲染的文件名, 以及对应的key值
	public static function htmls($key, $filename='')
    {
        if (empty($filename)) {
            self::$htmls = array();
        } else {
            self::$htmls[$key] = $filename;
        }
    }
    
    //渲染主页面, 将self::$htmls中其他已渲染的页面插入到主页面中
    public static function render($key)
    {
        if (empty($key)) {
            exit('Nothing~');
        }
    
        //渲染主页面内容
        $path = self::getRealPath(self::$htmls[$key]);
        $main = self::fetch($path);
        unset(self::$htmls[$key]);
        
        //渲染子页面内容, 并将内容插入到制定位置
        foreach (self::$htmls as $k => $filename) {
            $path = self::getRealPath($filename);
            $content = self::fetch($path);
            $main = str_replace('{{'.$k.'}}', $content, $main);
        }
        
		header("Content-type: text/html; charset=utf-8");
        exit($main);
    }
    
}
